#!/bin/bash -el

# This script generate archives and deploy applications using tsuru api.
#
# It depends on the following environment variables:
#
#   - TSURU_HOST: URL to the Tsuru API (for example: http://yourtsuru:8080)
#   - TSURU_TOKEN: the token to communicate with the API (generated with
#                  `tsurud token`, in the server).

while read oldrev newrev refname
do
    set +e
    echo $refname | grep -v tags/main$ | grep -q /main$
    status=$?
    set -e
    if [ $status = 0 ]; then
        COMMIT=${newrev}
    fi
done

if [ -z ${COMMIT} ]
then
    echo "ERROR: please push to main"
    exit 3
fi

git_archive_all() {
    REV=$1; FILE=$2; TMP_WORK_DIR=$3
    chmod 755 $TMP_WORK_DIR
    unset GIT_DIR GIT_WORK_TREE
    git clone -q $PWD $TMP_WORK_DIR &> /dev/null
    pushd $TMP_WORK_DIR > /dev/null
    git config advice.detachedHead false
    git checkout $REV > /dev/null
    git submodule update --init --recursive > /dev/null
    find -name .git -prune -exec rm -rf {} \; > /dev/null
    tar zcf /tmp/$FILE .
    popd > /dev/null
}

clean_up() {
    set +e
    rm /tmp/deploy-${APP_NAME}.log 2>/dev/null
    if [ -d ${TMP_WORK_DIR} ]; then
        rm -rf ${TMP_WORK_DIR} 2>/dev/null
    fi
    rm /tmp/${ARCHIVE_FILE_NAME} 2>/dev/null
    set -e
}

trap clean_up ERR EXIT

APP_DIR=${PWD##*/}
APP_NAME=${APP_DIR/.git/}
UUID=`python -c 'import uuid; print uuid.uuid4().hex'`
ARCHIVE_FILE_NAME=${APP_NAME}_${COMMIT}_${UUID}.tar.gz
TMP_WORK_DIR=$(mktemp -d)
git_archive_all $COMMIT $ARCHIVE_FILE_NAME $TMP_WORK_DIR
archive_url="/tmp/${ARCHIVE_FILE_NAME}"
url="${TSURU_HOST}/apps/${APP_NAME}/deploy"
curl -H "Authorization: bearer ${TSURU_TOKEN}" -F "file=@${archive_url}" -F "commit=${COMMIT}" -F "user=${TSURU_USER}" -s -N $url | tee /tmp/deploy-${APP_NAME}.log
tail -1 /tmp/deploy-${APP_NAME}.log | grep -q "^OK$"